// import React from 'react';
import React from './ireact/react';
// import ReactDOM from 'react-dom';
import ReactDOM from './ireact/react-dom';

console.log(<div>{123}</div>);

class Counter extends React.Component{
  static defaultProps = {
    name: '计数器'
  }

  constructor(props) {
    super(props);
    this.state = {number: 1};

    console.log('1 Counter constructor');
  }

  handleClick=(event)=>{
    this.setState({number: this.state.number + 1},()=>{
      console.log('Counter setState 回调, 应该在子组件重新渲染之后执行');
    })
  }

  render(){
    console.log('3 Counter render --- 重新计算新的虚拟dom');

    return (
      <div id={`counter-${this.state.number}`}>
        <p>{this.state.number}</p>
        <ChildCounter count={this.state.number}/>
        <button onClick={this.handleClick}>+</button>
      </div>
    );
  }

  componentDidMount(){
    console.log('4 Counter componentDidMount');

  }

  componentDidUpdate(){
    console.log('7 Counter componentDidUpdate');
  }
}

class ChildCounter extends React.Component {
  constructor(props) {
    console.log('ChildCounter constructor');
    super(props);
    this.state = {number: 1111};
    this.clientX = 0;
  }

  //从组件的新属性中映射出一个新的状态 (类似于之前的componentWillReceiveProps(nextProps))
  //和废弃的will receive props不一样，初始化时就会执行
  //设计为static 是为了 防止你在这里 this.setState 导致死循环
  static getDerivedStateFromProps(nextProps,prevState){
    console.log('ChildCounter getDerivedStateFromProps nextProps prevState:',nextProps,prevState);
    const {count} = nextProps;
    if (count % 2 === 0) {
      return {number: count * 2}; //返回的状态会自动合并
    }else if(count % 3 === 0){
      return {number: count * 3};
    }
    return null; //什么也不会做 并不会改变现有的state
  }

  render() {
    console.log('2 ChildCounter render');
    return <div id='child-counter'>
      <p>event.clientX:{this.clientX}</p>
      {this.state.number}
    </div>
  }

  componentDidMount(){
    console.log('3 ChildCounter componentDidMount');
    /*window.addEventListener('mousemove', (event) => {
      console.log('event:',event);
      this.clientX = event.clientX;
      this.forceUpdate()
    });*/
  }

  //getDerivedStateFromProps 更新时会在 shouldComponentUpdate 之前执行
  //并且 还会在初始化时执行(组件挂载时), 而shouldComponentUpdate和原来的receiveProps都不会
  /*shouldComponentUpdate(nextProps,nextState){
    console.log('5 ChildCounter shouldComponentUpdate');
    return nextProps.count % 3 === 0;
  }*/

  componentDidUpdate(){
    console.log('7 ChildCounter componentDidUpdate');
  }

  componentWillUnmount(){
    console.log('ChildCounter componentWillUnmount 组件将要卸载');
  }
}


ReactDOM.render((
  <Counter name={'计数器'}/>
), document.getElementById('root'));
